'use strict';

import AdminModel from '../../models/admin/admin'
import AddressComponent from '../../prototype/addressComponent'
import crypto from 'crypto'
import dtime from 'time-formater'

class Admin extends AddressComponent {
  constructor() {
    super()
    this.login = this.login.bind(this)
    this.encryption = this.encryption.bind(this)
  }
  /**
   * 登录Api
   * url /admin/login/
   * @param {String} user_name 用户名
   * @param {String} password 密码
   */
  async login (ctx,next) {
    // 解析数据
    const {user_name, password ,status=1} = ctx.request.body;
    
    // 参数验证
    try {
      if (!user_name) {
        throw new Error('用户名参数错误')
      } else if (!password) {
        throw new Error('密码参数错误')
      }
    } catch (err) {
      console.log(err.message, err);
      ctx.body = {
        status: 0,
        type: 'GET_ERROR_PARAM',
        message: err.message,
      }
      return
    }
    
    // 密码加密
    const newpassword = this.encryption(password);
    
    try {
      
      const admin = await AdminModel.findOne({ user_name })
      
      if (!admin) {
        const adminTip = status == 1 ? '管理员' : '超级管理员'
        const admin_id = await this.getId('admin_id');
        
        const cityInfo = await this.guessPosition(ctx.request);
        
        const newAdmin = {
          user_name,
          password: newpassword,
          id: admin_id,
          create_time: dtime().format('YYYY-MM-DD HH:mm'),
          admin: adminTip,
          status,
          city: cityInfo.city
        }
        await AdminModel.create(newAdmin)
        ctx.session.admin_id = admin_id;
        const token = await this.Token(user_name, newpassword ,admin_id)
        console.log(token);

        ctx.body = {
          status: 1,
          success: '注册管理员成功',
          token
        }
      } else if (newpassword.toString() != admin.password.toString()) {
        console.log('管理员登录密码错误');
        ctx.body = {
          status: 0,
          type: 'ERROR_PASSWORD',
          message: '该用户已存在，密码输入错误'
        }
      } else {
        ctx.session.admin_id = admin.id;
        const token = await this.Token(user_name, newpassword, admin.id)
        ctx.body = {
          status: 1,
          success: '登录成功',
          token
        }
      }
    } catch (err) {
      console.log('登录管理员失败', err);

      ctx.body = {
        status: 0,
        type: 'LOGIN_ADMIN_FAILED',
        message: '登录管理员失败',
      }
    }
  }
  /**
   * 密码加密封装
   * @param {*} password 密码
   */
  encryption(password) {
    const newpassword = this.Md5(this.Md5(password).substr(2, 7) + this.Md5(password));
    return newpassword
  }
  /**
   * Md5加密封装
   * @param {*} password 
   */
  Md5(password) {
    const md5 = crypto.createHash('md5');
    return md5.update(password).digest('base64');
  }

  /**
   * Token
   * @param {String} name
   * @param {Strinng} password
   * @param {Number} id
   */
  async Token (name,password,id) {
    return await this.getToken({ name, password, id })
  }
}

export default new Admin()
